package com.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.annotation.CurrentUser;
import com.web.annotation.LoginRequired;
import com.web.dao.UserDataMapper;
import com.web.domain.Response;
import com.web.entity.*;
import com.web.service.HomeService;
import com.web.service.JobService;
import com.web.service.SupplyService;
import com.web.service.UserDataService;
import com.web.utils.DateUtil;
import com.web.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/app")
public class InfoController extends BaseController{

    @Autowired
    private HomeService homeService;
    @Resource
    private UserDataMapper userDataMapper;
    @Autowired
    private JobService jobService;

    @Autowired
    private SupplyService supplyService;
    /**
     * 获取用户个人信息
     * @param info
     * @return
     */
    @PostMapping("/user/info/get")
    @ResponseBody
    public Response getUserInfo(@CurrentUser UserInfo info) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        info.setInviteCode(MD5Util.EncoderByMd5(info.getInviteCode()));
        info.setPersonalPerfection(userDataMapper.PersonalInformationPerfection(info.getUserId()));
        return Response.custom().ok().addParams(info);
    }

    /**
     * 获取需求分类列表
     * @return
     */
    @PostMapping("/demand/info")
    @LoginRequired
    @ResponseBody
    public Response DemandInfo(){
        return Response.custom().ok().addParams(infoService.allDemand());
    }

    /**
     * 获取专业列表
     * @return
     */
    @PostMapping("/career/info")
    @LoginRequired
    @ResponseBody
    public Response CareerInfo(){
        return Response.custom().ok().addParams(infoService.allCareer());
    }

    /**
     * 完善个人资料
     * @param info
     * @param sex
     * @param dateOfBirth
     * @param qqNumber
     * @param email
     * @param profession
     * @param interest
     * @return
     */
    @PostMapping("/perfect/info")
    @ResponseBody
    public Response PerfectInfo(@CurrentUser UserInfo info, String sex,String dateOfBirth,String qqNumber,String email,String profession,String interest){
        if (StringUtils.isBlank(sex) || StringUtils.isBlank(dateOfBirth) || StringUtils.isBlank(qqNumber) || StringUtils.isBlank(email)
            || StringUtils.isBlank(profession) || StringUtils.isBlank(interest)){
            return Response.custom().failure("缺少必要参数");
        }
        info.setSex(Integer.valueOf(sex));
        info.setDateOfBirth(DateUtil.dateFormat(Long.valueOf(dateOfBirth)));
        info.setQqNumber(qqNumber);
        info.setEmail(email);
        info.setProfession(profession);
        info.setInterest(interest);
        infoService.uploadUserInfo(info);
        return Response.custom().ok();
    }

    /**
     * 更新个人信息
     * @param info
     * @param userInfo
     * @return
     */
    @PostMapping("/modify/info")
    @ResponseBody
    public Response modifyInfo(@CurrentUser UserInfo info, ModifyUserInfo userInfo){

        UserInfo user = infoService.info("user_id",info.getUserId());

        if(user!=null){
            info.setAvatar(userInfo.getAvatar());
            info.setNickname(userInfo.getNickname());
            info.setSex(userInfo.getSex());
            info.setDateOfBirth(userInfo.getDateOfBirth());
            info.setLatitude(userInfo.getLatitude());
            info.setLongitude(userInfo.getLongitude());
            info.setQqNumber(userInfo.getQqNumber());
            info.setEmail(userInfo.getEmail());
            info.setUserId(userInfo.getUserId());
            infoService.uploadUserInfo(info);
            return Response.custom().ok();
        }
       return Response.custom().failure("系统异常暂时未查找到您的信息！");
    }

    /**
     * 实名认证
     * @param info
     * @param certification
     * @return
     */
    @PostMapping("/certification/user")
    @ResponseBody
    public Response certificationUser(@CurrentUser UserInfo info, UserCertification certification){
        if (StringUtils.isBlank(String.valueOf(certification.getType()))){
            return Response.custom().failure("认证类型不能为空!");
        }

        //查询之前是否提交过认证
        UserCertification userCertification = selectCertification(info.getUserId());
        if (userCertification == null){
            certification.setUserId(info.getUserId());
            certification.setAuthStatus(1);
            switch (certification.getType()){
                case 1:
                    if (StringUtils.isBlank(certification.getRealname()) || StringUtils.isBlank(certification.getIdCard()) || StringUtils.isBlank(certification.getCardZ()) || StringUtils.isBlank(certification.getCardF())){
                        return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                    }
                    infoService.addCertification(certification);
                    return Response.custom().ok();
                case 2:
                    if (StringUtils.isBlank(certification.getRealname()) || StringUtils.isBlank(certification.getIdCard()) || StringUtils.isBlank(certification.getCardZ()) || StringUtils.isBlank(certification.getCardF())
                            || StringUtils.isBlank(certification.getTechCard()) || StringUtils.isBlank(certification.getTechId())){
                        return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                    }
                    TechInfo techInfo = new TechInfo();
                    techInfo.setUserId(info.getUserId());
                    infoService.addTech(techInfo);
                    infoService.addCertification(certification);
                    return Response.custom().ok();
                default:
                    return Response.custom().failure("认证类型错误!");
            }
        }else {
            certification.setId(userCertification.getId());
            switch (userCertification.getAuthStatus()){
                case 1:
                    return Response.custom().failure("认证中,无需再次提交!");
                case 2:
                    switch (userCertification.getType()){
                        case 1:
                            if (certification.getType() == 1){
                                return Response.custom().failure("您已成功认证个人认证,无需再次认证");
                            }
                            if (StringUtils.isBlank(certification.getRealname()) || StringUtils.isBlank(certification.getIdCard()) || StringUtils.isBlank(certification.getCardZ()) || StringUtils.isBlank(certification.getCardF())
                                    || StringUtils.isBlank(certification.getTechCard()) || StringUtils.isBlank(certification.getTechId())){
                                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                            }
                            //判断企业信息是否存在
                            if (infoService.selectTechInfo(info.getUserId()) == null){
                                //添加企业信息
                                TechInfo techInfo = new TechInfo();
                                techInfo.setUserId(info.getUserId());
                                infoService.addTech(techInfo);
                            }
                            certification.setUserId(info.getUserId());
                            certification.setAuthStatus(1);
                            infoService.uploadCertification(certification);
                            return Response.custom().ok();
                        case 2:
                            return Response.custom().failure("您已成功认证企业认证,无需再次认证");
                        default:
                            return Response.custom().failure("认证类型错误!");
                    }
                case 3:
                    certification.setUserId(info.getUserId());
                    switch (certification.getType()){
                        case 1:
                            if (StringUtils.isBlank(certification.getRealname()) || StringUtils.isBlank(certification.getIdCard()) || StringUtils.isBlank(certification.getCardZ()) || StringUtils.isBlank(certification.getCardF())){
                                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                            }
                            certification.setAuthStatus(1);
                            infoService.uploadCertification(certification);
                            return Response.custom().ok();
                        case 2:
                            if (StringUtils.isBlank(certification.getRealname()) || StringUtils.isBlank(certification.getIdCard()) || StringUtils.isBlank(certification.getCardZ()) || StringUtils.isBlank(certification.getCardF())
                                    || StringUtils.isBlank(certification.getTechCard()) || StringUtils.isBlank(certification.getTechId())){
                                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                            }
                            certification.setAuthStatus(1);
                            infoService.uploadCertification(certification);
                            return Response.custom().ok();
                        default:
                            return Response.custom().failure("认证类型错误!");
                    }
                default:
                    return Response.custom().failure("认证类型错误!");
            }
        }
    }

    /**
     * 设计师认证
     * @param info
     * @param designer
     * @return
     */
    @PostMapping("/designer/user")
    @ResponseBody
    public Response designerUser(@CurrentUser UserInfo info, UserDesigner designer){
        //查询之前是否提交过认证
        UserDesigner userDesigner = infoService.findUserDesigner(info.getUserId());
        if (userDesigner == null){
            designer.setUserId(info.getUserId());
            designer.setAuthStatus("1");
            if (StringUtils.isBlank(designer.getName()) || StringUtils.isBlank(designer.getLogo()) || StringUtils.isBlank(designer.getCreateYear()) || StringUtils.isBlank(designer.getCaseExperience())
                || StringUtils.isBlank(designer.getSkill())){
                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
            }
            Response response = infoService.uploadCurrency(info.getUserId(),null,null,1);
            if (response.getStatus() != 900000){
                return response;
            }
            infoService.addDesigner(designer);
            return Response.custom().ok();
        }else {
            designer.setId(userDesigner.getId());
            designer.setUserId(info.getUserId());
            switch (userDesigner.getAuthStatus()){
                case "1":
                    return Response.custom().failure("认证中,无需再次提交!");
                case "2":
                    return Response.custom().failure("您已成功认证工作室,无需再次认证");
                case "3":
                    if (StringUtils.isBlank(designer.getName()) || StringUtils.isBlank(designer.getLogo()) || StringUtils.isBlank(designer.getCreateYear()) || StringUtils.isBlank(designer.getCaseExperience())
                            || StringUtils.isBlank(designer.getSkill())){
                        return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                    }
                    Response response = infoService.uploadCurrency(info.getUserId(),null,null,1);
                    if (response.getStatus() != 900000){
                        return response;
                    }
                    designer.setAuthStatus("1");
                    infoService.uploadDesigner(designer);
                    return Response.custom().ok();
                default:
                    return Response.custom().failure("认证类型错误!");
            }
        }
    }


    /**
     * 专家认证
     * @param info
     * @param expert
     * @return
     */
    @PostMapping("/expert/user")
    @ResponseBody
    public Response expertUser(@CurrentUser UserInfo info, UserExpert expert){
        //查询之前是否提交过认证
        UserExpert userExpert = infoService.findUserExpert(info.getUserId());
        if (userExpert == null){
            expert.setUserId(info.getUserId());
            expert.setAuthStatus("1");
            if (StringUtils.isBlank(expert.getRealname()) || StringUtils.isBlank(expert.getSex()) || StringUtils.isBlank(expert.getMobile()) || StringUtils.isBlank(expert.getEdu())
                    || StringUtils.isBlank(expert.getCity()) || StringUtils.isBlank(expert.getWorkExperience()) || StringUtils.isBlank(expert.getProfessionalSkill())
                    || StringUtils.isBlank(expert.getExpertClass())){
                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
            }
            infoService.addExpert(expert);
            return Response.custom().ok();
        }else {
            expert.setId(userExpert.getId());
            expert.setUserId(info.getUserId());
            switch (userExpert.getAuthStatus()){
                case "1":
                    return Response.custom().failure("认证中,无需再次提交!");
                case "2":
                    return Response.custom().failure("您已成功认证专家,无需再次认证");
                case "3":
                    if (StringUtils.isBlank(expert.getRealname()) || StringUtils.isBlank(expert.getSex()) || StringUtils.isBlank(expert.getMobile()) || StringUtils.isBlank(expert.getEdu())
                            || StringUtils.isBlank(expert.getCity()) || StringUtils.isBlank(expert.getWorkExperience()) || StringUtils.isBlank(expert.getProfessionalSkill())
                            || StringUtils.isBlank(expert.getExpertClass())){
                        return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                    }
                    expert.setAuthStatus("1");
                    infoService.uploadExpert(expert);
                    return Response.custom().ok();
                default:
                    return Response.custom().failure("认证类型错误!");
            }
        }
    }



    /**
     *供应商认证
     * @param info
     * @param supply
     * @return
     */
    @PostMapping("/supply/user")
    @ResponseBody
    public Response supplyUser(@CurrentUser UserInfo info, UserSupply supply,String techcreateTime){
        //查询之前是否提交过认证
        UserSupply userSupply = infoService.findUserSupply(info.getUserId());
        if (userSupply == null){
            supply.setUserId(info.getUserId());
            supply.setAuthStatus(1);
            supply.setTechCreateTime(DateUtil.dateFormat(Long.valueOf(techcreateTime)));
            if (StringUtils.isBlank(supply.getSupplyClassId()) || StringUtils.isBlank(supply.getTechName()) || StringUtils.isBlank(supply.getRealname()) || StringUtils.isBlank(supply.getIdCard())
                    || StringUtils.isBlank(supply.getIdCardZ()) || StringUtils.isBlank(supply.getIdCardF()) || StringUtils.isBlank(supply.getTechCard())
                    || StringUtils.isBlank(supply.getLogo()) || StringUtils.isBlank(techcreateTime) || StringUtils.isBlank(supply.getTechCity()) || StringUtils.isBlank(supply.getTechMobile())
                    || StringUtils.isBlank(supply.getTechBusiness()) || StringUtils.isBlank(supply.getTechSkill())){
                return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
            }

            infoService.addSupply(supply);
            return Response.custom().ok();
        }else {
            supply.setId(userSupply.getId());
            supply.setUserId(info.getUserId());
            supply.setAuthStatus(1);
            supply.setTechCreateTime(DateUtil.dateFormat(Long.valueOf(techcreateTime)));
            switch (userSupply.getAuthStatus()){
                case 1:
                    return Response.custom().failure("认证中,无需再次提交!");
                case 2:
                    return Response.custom().failure("您已成功认证供应商,无需再次认证");
                case 3:
                    if (StringUtils.isBlank(supply.getSupplyClassId()) || StringUtils.isBlank(supply.getTechName()) || StringUtils.isBlank(supply.getRealname()) || StringUtils.isBlank(supply.getIdCard())
                            || StringUtils.isBlank(supply.getIdCardZ()) || StringUtils.isBlank(supply.getIdCardF()) || StringUtils.isBlank(supply.getTechCard())
                            || StringUtils.isBlank(supply.getLogo()) || StringUtils.isBlank(techcreateTime) || StringUtils.isBlank(supply.getTechCity()) || StringUtils.isBlank(supply.getTechMobile())
                            || StringUtils.isBlank(supply.getTechBusiness()) || StringUtils.isBlank(supply.getTechSkill())){
                        return Response.custom().failure("认证参数缺少,请确认无误后,再次提交!");
                    }
                    infoService.uploadSupply(supply);
                    return Response.custom().ok();
                default:
                    return Response.custom().failure("认证类型错误!");
            }
        }
    }



    /**
     * 上传简历
     * @param info
     * @param userJob
     * @return
     */
    @PostMapping("/upload/user/job")
    @ResponseBody
    public Response uploadUserJob(@CurrentUser UserInfo info,UserJob userJob){
        UserJob job = infoService.findUserJob(info.getUserId());
        if (job == null){
            userJob.setUserId(info.getUserId());
            infoService.addUserJob(userJob);
            return Response.custom().ok();
        }else{
            job.setUserId(info.getUserId());
            job.setPosition(userJob.getPosition());
            job.setEmail(userJob.getEmail());
            job.setExpertise(userJob.getExpertise());
            job.setSex(userJob.getSex());
            job.setMobile(userJob.getMobile());
            job.setWorkYear(userJob.getWorkYear());
            job.setTech(userJob.getTech());
            job.setIsIncumbent(userJob.getIsIncumbent());
            infoService.modifyJob(job);
            return Response.custom().ok();
        }
    }

    /**
     * 上传项目经验
     * @param info
     * @return
     */
    @PostMapping("/upload/user/experience")
    @ResponseBody
    public Response uploadUserExperience(@CurrentUser UserInfo info, String theme, String synopsis, String openTime, String endTime ){
        if(synopsis == null || openTime == null || endTime == null){
            return Response.custom().failure("缺少必要参数！");
        }
        UserExperience experience = new UserExperience();
        experience.setUserId(info.getUserId());
        experience.setTheme(theme);
        experience.setSynopsis(synopsis);
        experience.setOpenTime(DateUtil.dateFormat(Long.valueOf(openTime)));
        experience.setEndTime(DateUtil.dateFormat(Long.valueOf(endTime)));
        experience.setCreateTime(new Date());
        experience.setModifyTime(new Date());
        infoService.uploadUserExperience(experience);
        return Response.custom().ok();
    }





    /**
     * 上传项目案例
     * @param info
     * @param userCase
     * @return
     */
    @PostMapping("/upload/user/case")
    @ResponseBody
    public Response uploadUserCase(@CurrentUser UserInfo info,UserCase userCase){
        userCase.setUserId(info.getUserId());
        infoService.uploadUserCase(userCase);
        return Response.custom().ok();
    }


    /**
     * 获取用户简历信息
     * @param info
     * @return
     */
    @PostMapping("/get/user/job")
    @ResponseBody
    public Response getUserExperience(@CurrentUser UserInfo info){
        Map<String,Object> map =  new HashMap<>();
        UserJob job = infoService.findUserJob(info.getUserId());
        map.put("job",job == null ? new UserJob():job);
        map.put("case",infoService.myCase(info.getUserId()));
        map.put("experience",infoService.myExperience(info.getUserId()));
        return Response.custom().ok().addParams(map);
    }


    /**
     * 获取我邀请的好友(包括我的下线邀请的,算上自己默认三级)
     * @param info
     * @param pageNum
     * @return
     */
    @PostMapping("/invite/info")
    @ResponseBody
    public Response InviteInfo(@CurrentUser UserInfo info,Integer pageNum){
        PageHelper.startPage(pageNum,10);
        List<InviteInfo> blackUserList = infoService.myInviteInfo(info.getInviteCode());
        PageInfo pageInfo = new PageInfo(blackUserList,10);
        if(pageNum > pageInfo.getPages()){
            return Response.custom().ok().addParams(new List[0]);
        }else{
            return Response.custom().ok().addParams(pageInfo.getList());
        }
    }


    /**
     * 删除发布统一接口
     * @param info
     * @param type 1.需求,2.招聘,3.求职（零工）,4供应,5四闲,6动态,7.技术,8.问题
     * @param typeId 类型id
     * @return
     */
    @PostMapping("/delete/all/release")
    public Response DeleteALLRelease(@CurrentUser UserInfo info,Integer type,Integer typeId){
        if(type == null || typeId == null){
            return Response.custom().failure("缺少必要参数！");
        }
        switch (type){
            case 1:
                MyDemand myDemand = homeService.findMyDemand(info.getUserId(),typeId);
                if(myDemand != null ){
                    homeService.DeleteMyDemand(typeId);
                   return Response.custom().ok();
                }
                   return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
            case 2:
                TechRecriitment techRecriitment = jobService.findMyTechRecriitment(info.getUserId(),typeId);
                if(techRecriitment != null ){
                    jobService.DeleteMyTechRecriitment(typeId);
                    return Response.custom().ok();
                }
                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
            case 3:
                JobHunting jobHunting = jobService.findMyjobHunting(info.getUserId(),typeId);
                if(jobHunting != null ){
                    jobService.DeleteMyjobHunting(typeId);
                    return Response.custom().ok();
                }
                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
            case 4:
                Supply supply = supplyService.findMySupply(info.getUserId(),typeId);
                if(supply != null ){
                    supplyService.DeleteMySupply(typeId);
                    return Response.custom().ok();
                }
                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
            case 5:
                LeaveUnusedInfo leaveUnusedInfo = supplyService.findMyLeaveUnusedInfo(info.getUserId(),typeId);
                if(leaveUnusedInfo != null ){
                    supplyService.DeleteLeaveUnusedInfo(typeId);
                    return Response.custom().ok();
                }
                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
//            case 6:
//                Supply supply = supplyService.findMySupply(info.getUserId(),typeId);
//                if(supply != null ){
//                    supplyService.DeleteMySupply(typeId);
//                    return Response.custom().ok().addParams(supply);
//                }
//                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
//            case 7:
//                Supply supply = supplyService.findMySupply(info.getUserId(),typeId);
//                if(supply != null ){
//                    supplyService.DeleteMySupply(typeId);
//                    return Response.custom().ok().addParams(supply);
//                }
//                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
//            case 8:
//                Supply supply = supplyService.findMySupply(info.getUserId(),typeId);
//                if(supply != null ){
//                    supplyService.DeleteMySupply(typeId);
//                    return Response.custom().ok().addParams(supply);
//                }
//                return Response.custom().ok().failure("本条内容您无法操作！或不存在！");
            default:
                return Response.custom().failure("类型不存在!");
        }

    }

}
